/*
 * Copyright (C) 2001-2005 Pleasant nightmare studio
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package org.pleasantnightmare.acake.errorhandling;

import javax.tools.Diagnostic;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.MessageFormat;

/**
 * Handles errors that processors are dispatching and presents them
 * to user in clean, concise way.
 *
 * @author deus
 * @version 1.0
 * @since Nov 16, 2009 9:05:41 AM
 */
public class SimpleErrorHandler implements ErrorHandler {
    private Writer writer;

    public SimpleErrorHandler() {
        this(new OutputStreamWriter(System.err));
    }

    public SimpleErrorHandler(Writer writer) {
        this.writer = writer;
    }

    @Override
    public void report(CheckError checkError) {
        String line = line(checkError.getLevel(), checkError.getErrorCode(), checkError.getMessage());
        try {
            writer.write(line);
            writer.flush();
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    @Override
    public void printMessage(Diagnostic.Kind note, String message) {
        try {
            writer.write("[" + note.toString() + "]" + message);
            writer.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String line(int level, int errorCode, String message) {
        return MessageFormat.format("{0} {1}: {2}\n", levelToString(level), errorCode, message);
    }

    private String levelToString(int level) {
        if (level < CheckError.DEFAULT_INFO_LEVEL)
            return "INFO";
        else if (level < CheckError.DEFAULT_WARN_LEVEL)
            return "WARNING";
        else
            return "ERROR";
    }
}
